<template>
  <view class="index-wrapper">
    <view class="userinfo-itemlist">
      <view
        v-for="(item, index) in site.sites"
        :key="index"
        class="userinfo-item"
        @tap="switchSite(item.id)"
      >
        <view class="item-left">
          <span style="padding-left: 0"> {{ item.name }}</span>
        </view>
        <view v-if="item.currSite" class="item-right">
          <text class="iconfont">&#xe65a;</text>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
import { mapState } from "vuex";
import { switchSiteReq } from "@/services/auth";
export default {
  name: "",
  components: {},
  props: {},
  data() {
    return {
      sites: [],
      currentSite: null
    };
  },
  computed: {
    ...mapState(["site"])
  },
  watch: {},
  created() {
    this.sites = this.site.sites;
    console.log("debug log --> ", this.sites)

    this.currentSite = this.site.currentSite;
  },
  mounted() {},
  methods: {
    goBack() {
      uni.redirectTo({
        url: "/pages/index/index"
      });
    },
    switchSite(siteId) {
      if (this.site.currentSite.id === siteId) {
        this.goBack();
      } else {
        switchSiteReq(siteId)
          .then(res => {
            uni.setStorageSync("token", res.token);
            this.$store.commit("register/updateToken", res.token);
            uni.showToast({
              title: "租户切换成功",
              icon: "none",
              duration: 2000
            });
            this.goBack();
          })
          .catch(err => {
            uni.showToast({
              title: err,
              icon: "none",
              duration: 2000
            });
          });
      }
    }
  }
};
</script>
